<template>
  <div class="app-container">
    <h4 class="form-header h4">课时信息</h4>
    <el-form ref="lesson" :model="lesson" label-width="80px">
      <el-row>
        <el-col :span="6" :offset="2">
          <el-form-item label="日期" prop="createTime">
            <el-input v-model="lesson.createTime" :readonly="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="2">
          <el-form-item label="教练" prop="coachName">
            <el-input  v-model="lesson.coachName" :readonly="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="2">
          <el-form-item label="场馆" prop="stadiumName">
            <el-input  v-model="lesson.stadiumName" :readonly="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="2">
          <el-form-item label="班次" prop="classesName">
            <el-input  v-model="lesson.classesName" :readonly="true" />
          </el-form-item>
        </el-col>
        <el-col :span="6" :offset="2">
          <el-form-item label="备注" prop="remark">
            <el-input  v-model="lesson.remark" :readonly="true" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <h4 class="form-header h4">学员信息: 共 {{total}} 人</h4>

    <el-table v-loading="loading" :row-key="getRowKey" @row-click="clickRow" ref="table" :data="lessonstudentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{(pageNum - 1) * pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="学号" align="center" prop="studentCode" />
      <el-table-column label="学员姓名" align="center" prop="studentName" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['puyu:lesson:editStudent']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="checkDeleteLessonStudent()"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pageNum"
      :limit.sync="pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学员课时点名对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学员" prop="studentCodeName"  v-if="form.lessonStudentId == null">
          <el-autocomplete class="inline-input" value-key="label"
            v-model="studentInfo"
            :fetch-suggestions="queryStudentCode"
            placeholder="请输入学号或学员姓名"
            @select="handleStudentCode"></el-autocomplete>
        </el-form-item>
        </el-form-item>
        <el-form-item label="学号" prop="studentCode" v-if="form.lessonStudentId != null">
          <el-input v-model="form.studentCode" placeholder="请输入学号" disabled />
        </el-form-item>
        <el-form-item label="学员姓名" prop="studentName" v-if="form.lessonStudentId != null">
          <el-input v-model="form.studentName" placeholder="请输入学员姓名" disabled />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-form label-width="100px">
      <el-form-item style="text-align: center;margin-left:-120px;margin-top:30px;">
        <el-button type="primary" @click="handleAdd()"  v-if="checkAddLessonStudent()">添加</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { parseTime } from "../../../utils/ruoyi";
import { listLesson, listStudent, getLesson, delLesson, addLesson, updateLesson, getStudent, addStudent, updateStudent, delStudent } from "@/api/puyu/lesson";
import { listNotExpiredStudents } from "@/api/puyu/student";

export default {
  name: "LessonStudents",
  dicts: ['puyu_classes', 'puyu_stadium'],
  data() {
    return {
       // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 学员表格数据
      studentList: [],
      // 学员课时点名表格数据
      lessonstudentList: [],
      pageNum: 1,
      pageSize: 10,
      // 选中数组
      ids: [],
      studentInfo: "",
      // 用户信息
      form: {},
      // 课时信息
      lesson: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 表单校验
      rules: {
        coachId: [
          { required: true, message: "教练ID不能为空", trigger: "blur" }
        ],
        studentName: [
          { required: true, message: "学员姓名不能为空", trigger: "blur" }
        ],
      },
    };
  },
  created() {
    const lessonId = this.$route.params && this.$route.params.lessonId;
    if (!lessonId) {
      return;
    }
    this.lesson.lessonId = lessonId;
    this.loading = true;
    // 查询参数
    let queryParams = {
      lessonId: lessonId
    }
    getLesson(lessonId).then((response) => {
      this.lesson.deptId = response.data.deptId;
      this.lesson.coachId = response.data.coachId;
      this.lesson.createTime = parseTime(response.data.createTime, '{y}-{m}-{d}');
      this.lesson.checkTime = response.data.createTime;
      this.lesson.coachName = response.data.coachName;
      this.lesson.stadiumName = this.selectDictLabel(this.dict.type.puyu_stadium, response.data.stadiumId);
      this.lesson.classesName = this.selectDictLabel(this.dict.type.puyu_classes, response.data.classesId);
      this.lesson.remark = response.data.remark;
      this.loading = false;
    });
    // 获取学员点名列表
    this.getList();
    // 获取学员下拉列表
    this.getStudentLsit();
  },
  methods: {
    /** 查询学员列表 */
    getStudentLsit() {
      listNotExpiredStudents().then(response => {
        this.studentList = response.data;
      });
    },
    /** 查询学员课时点名列表 */
    getList() {
      if (!this.lesson.lessonId) {
        return;
      }
      // this.loading = true;
      // 查询参数
      let queryParams = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        lessonId: this.lesson.lessonId
      }
      listStudent(queryParams).then((response) => {
        this.lessonstudentList = response.rows;
        this.total = response.total;
        // this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        lessonStudentId: null,
        deptId: null,
        lessonId: this.lesson.lessonId,
        coachId: this.lesson.coachId,
        studentId: null,
        studentCode: null,
        studentName: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 单击选中行数据 */
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.lessonStudentId);
      this.single = selection.length!==1;
      this.multiple = !selection.length;
    },
    // 保存选中的数据编号
    getRowKey(row) {
      return row.lessonStudentId;
    },
    queryStudentCode(queryString, cb) {
        var studentList = this.studentList;
        let list = studentList.map((tmp) => {
          return {
            label: tmp.studentCode + '-' + tmp.studentName,
            value: tmp.studentId
          }
        })
        var results = queryString
            ? list.filter(this.filterStudentCode(queryString))
            : list;
        // 调用 callback 返回建议列表的数据
        cb(results);
    },
    filterStudentCode(queryString) {
        return (student) => {
            return (
                student.label
                    .toLowerCase()
                    .indexOf(queryString.toLowerCase()) > -1
            );
        };
    },
    //选中
    handleStudentCode(info) {
        let item = this.studentList.filter((tmp) => tmp.studentId === info.value)[0];
        this.form.userId = item.userId;
        this.form.deptId = item.deptId;
        this.form.studentId = item.studentId;
        this.form.studentCode = item.studentCode;
        this.form.studentName = item.studentName;
    },
    /** 关闭按钮 */
    close() {
      const obj = { path: "/puyu/lesson" };
      this.$tab.closeOpenPage(obj);
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学员课时点名";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const lessonStudentId = row.lessonStudentId || this.ids
      getStudent(lessonStudentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学员课时点名";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.coachId = this.lesson.coachId;
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.lessonStudentId != null) {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.studentInfo = '';
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const lessonStudentIds = row.lessonStudentId || this.ids;
      this.$modal.confirm('是否确认删除学员课时点名编号为"' + lessonStudentIds + '"的数据项？').then(function() {
        return delStudent(lessonStudentIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 计算两个时间差几小时 */
    hoursBetween(time1, time2) {
      // 将时间字符串转换为Date对象
        const date1 = new Date(time1);
        const date2 = new Date(time2);
        // 计算两个时间的时间戳差值
        const diff = Math.abs(date2.getTime() - date1.getTime());
        // 将差值转换为小时
        const hours = diff / (1000 * 60 * 60);
        // 返回结果
        return hours;
    },
    /** 校验是否显示添加学员点名按钮 */
    checkAddLessonStudent() {
      let hours = this.hoursBetween(parseTime(this.lesson.checkTime, '{y}-{m}-{d} {h}:{i}:{s}'), parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'));
      return this.$auth.hasPermi("puyu:lessons:addStudent") &&  hours <= 3 ;
    },
    /** 校验是否显示删除操作 */
    checkDeleteLessonStudent() {
      let hours = this.hoursBetween(parseTime(this.lesson.checkTime, '{y}-{m}-{d} {h}:{i}:{s}'), parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'));
      return this.$auth.hasPermi("puyu:lesson:removeStudent") &&  hours <= 3 ;
    },
  },
};
</script>
